import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_view/photo_view.dart';

class ImagePickerPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ImagePickerPageState();
  }
}

class _ImagePickerPageState extends State<ImagePickerPage> {
  File? _image;
  final picker = ImagePicker();

  Future getImage(ImageSource source) async {
    var image = await picker.pickImage(source: source);
    if (image == null) return;

    setState(() {
      _image = File(image.path);
      print(_image?.path);
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Image Picker Example'),
      ),
      body: new Center(
        child: _image == null
            ? new Text('No image selected.')
            : new PhotoView(imageProvider: FileImage(_image!)),
      ),
      floatingActionButton: new FloatingActionButton(
        tooltip: 'Pick Image',
        child: new Icon(Icons.add_a_photo),
        onPressed: () {
          showModalBottomSheet(
              context: context,
              builder: (context) {
                return CupertinoActionSheet(
                  title: Text("请选择"),
                  actions: <Widget>[
                    ListTile(
                      title: Center(
                        child: Text("拍照"),
                      ),
                      onTap: () {
                        getImage(ImageSource.camera);
                        Navigator.pop(context);
                      },
                    ),
                    ListTile(
                      title: Center(
                        child: Text("图库"),
                      ),
                      onTap: () {
                        getImage(ImageSource.gallery);
                        Navigator.pop(context);
                      },
                    ),
                  ],
                );
              });
        },
      ),
    );
  }
}
